package com.szjlc.requestbodyadvice.advice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

/**
 * 请求入参advice<br/>
 * RequestBodyAdvice仅对使用了@RqestBody注解的生效 , 因为它原理上还是AOP, 所以GET方法是不会操作的。
 * @author steve
 * @since 2023-10-29 22:41
 */
@Slf4j
@RestControllerAdvice
public class MyRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);
        log.info("请求url:{}", Arrays.toString(requestMapping.value()));
        log.info("请求入口：{}", parameter.getExecutable());
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("请求参数：{}", body);
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return null;
    }
}
